package com.example.demo.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.ribbon.proxy.annotation.Http;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * Created by zhangjiawen on 2019/5/29.
 */
@Component
public class OrderRateLimiterFilter extends ZuulFilter {
    //设置令牌数量
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(10);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -4;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();
        String requestURI = request.getRequestURI();
        if("/apigateway/product/api/v1/product/getList".equalsIgnoreCase(requestURI)){
            return true;
        }


        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        if(!RATE_LIMITER.tryAcquire()) {//如果拿不到令牌说明超限
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            System.out.println("流量过大请稍后再试……");
        }
        return null;
    }
}
